﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SimpleDbBrowser.ViewModel;

namespace SimpleDbBrowser.View.ViewContainers
{
    /// <summary>
    /// Interaction logic for DialogViewContainer.xaml
    /// </summary>
    public partial class DialogViewContainer : Window
    {
        public DialogViewContainer()
        {
            this.InitializeCommands();
            this.InitializeComponent();
        }

        public ICommittableViewModel ViewModel { get; private set; }

        public FrameworkElement View { get; private set; }

        public ICommand Commit { get; private set; }

        public ICommand Apply { get; private set; }

        public void AssignView(ICommittableViewModel viewModel, FrameworkElement view)
        {
            this.ViewModel = viewModel;
            this.View = view;

            this.View.DataContext = this.ViewModel;
            this.ViewHost.Child = this.View;
        }

        private void InitializeCommands()
        {
            this.Commit = new RelayCommand(this.ExecuteCommit);
            this.Apply = new RelayCommand(this.ExecuteApply, this.CanExecuteApply);
        }
        
        private void ExecuteCommit(object parameter)
        {
            if (this.ViewModel.Commit.CanExecute(parameter))
            {
                this.ViewModel.Commit.Execute(parameter);
            }

            this.Close();
        }

        private bool CanExecuteApply(object parameter)
        {

            if (this.ViewModel == null) return false;
            return this.ViewModel.Commit.CanExecute(parameter);
        }

        private void ExecuteApply(object parameter)
        {
            if (!this.CanExecuteApply(parameter)) return;

            this.ViewModel.Commit.Execute(parameter);
        }
    }
}
